package sg.edu.nus.iss.billing.template;

import java.util.ArrayList;
import java.util.List;

import sg.edu.nus.iss.billing.exception.TemplateEngineException;
import sg.edu.nus.iss.billing.template.interfaces.ParseAction;
import sg.edu.nus.iss.billing.template.interfaces.ParseActionProcessor;

/**
 * @author Daniel
 *
 */
public class BasicParseActionProcessor implements ParseActionProcessor {
	
	private List<ParseAction> parseActionList;
	private BillingTemplate saTemplate;
	private String parsedTemplate;
	private boolean parseComplete = false;
	
	public BasicParseActionProcessor(BillingTemplate saTemplate) {
		parseActionList = new ArrayList<ParseAction>();
		this.saTemplate = saTemplate;
		this.parsedTemplate = saTemplate.getTemplateFileContent();
	}
	
	public void addParseAction(ParseAction parseAction) {
		parseActionList.add(parseAction);
	}
	
	public void addParseActionList(List<ParseAction> parseActionList) {
		this.parseActionList.addAll(parseActionList);
	}
	
	public void process() throws TemplateEngineException {
		if (this.saTemplate == null) {
			throw new TemplateEngineException("Processor cannot be run without properly setup of template.");
		} else {
			System.out.println("Template: " + saTemplate.getTemplateFileName());
		}
		
		try {
			preProcess();
	
			for (int i=0; i < parseActionList.size(); i++) {
				//System.out.println("Parsing: " + parseActionList.get(i).getParseKey() + " starts");
				this.parsedTemplate = parseActionList.get(i).parse(this.parsedTemplate);
				//System.out.println("Parsing: " + parseActionList.get(i).getParseKey() + " end");
			}
			//System.out.println("Successful Template printed below");
			//System.out.println(this.parsedTemplate);
			
			postProcess();
			
			this.parseComplete = true;
		} catch (Exception e) {
			throw new TemplateEngineException(e.getMessage());
		}
	}
	
	public String getParsedString() {
		return this.parsedTemplate;
	}
	public void preProcess() throws TemplateEngineException {
		System.out.println("WARN: Preprocess is not defined yet");
	}
	public void postProcess() throws TemplateEngineException {
		System.out.println("WARN: Postprocess is not defined yet");
	}
	
	
	
	

}
